<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="资讯分类" prop="categoryId">
        <el-input
          v-model="selectedCategoryName"
          placeholder="请选择资讯分类"
          readonly
          class="!w-400px"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openCategoryDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="封面图片" prop="coverImage">
        <UploadImg v-model="formData.coverImage" />
      </el-form-item>
      <el-form-item label="资讯标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入资讯标题" class="!w-400px" />
      </el-form-item>
      <el-form-item label="资讯详情" prop="content">
        <Editor v-model="formData.content" height="400px" />
      </el-form-item>
      <el-form-item label="图片文件" prop="files">
        <UploadFile 
          v-model="formData.files" 
          :limit="10"
          :file-type="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'pdf', 'doc', 'docx', 'xls', 'xlsx']"
          :file-size="10"
        />
        <div class="form-tip">支持上传图片和文件，最多10个，单个文件不超过10MB</div>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input v-model="formData.tags" placeholder="请输入标签，多个标签用逗号分隔" class="!w-400px" />
      </el-form-item>
      <!-- <el-form-item label="摘要" prop="summary">
        <el-input v-model="formData.summary" type="textarea" :rows="3" placeholder="请输入摘要" />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">停用</el-radio>
          <el-radio :value="1">开启</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" placeholder="请输入排序" controls-position="right" class="!w-200px" />
      </el-form-item>
      <!-- <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
          v-model="formData.publishTime"
          type="datetime"
          value-format="x"
          placeholder="选择发布时间"
          class="!w-400px"
        />
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input v-model="formData.source" placeholder="请输入来源" class="!w-400px" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 分类选择弹窗 -->
  <ConsultCategorySelectDialog ref="categoryDialogRef" @confirm="handleCategoryConfirm" />
</template>
<script setup lang="ts">
import { ConsultInfoApi, ConsultInfoVO } from '@/api/system/consultinfo'
import ConsultCategorySelectDialog from './ConsultCategorySelectDialog.vue'
import type { consultCategoryVO } from '@/api/system/consultCategory'

/** 资讯信息 表单 */
defineOptions({ name: 'ConsultInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const categoryDialogRef = ref() // 分类选择弹窗
const selectedCategoryName = ref('') // 选中的分类名称

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  categoryId: undefined,
  coverImage: undefined,
  title: undefined,
  content: undefined,
  files: '', // 改为空字符串，用于存储逗号分隔的URL
  tags: undefined,
  summary: undefined,
  status: 1,
  sort: 0,
  publishTime: undefined,
  source: undefined,
})
const formRules = reactive({
  categoryId: [{ required: true, message: '分类ID不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '资讯标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '资讯详情不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开分类选择弹窗 */
const openCategoryDialog = () => {
  categoryDialogRef.value?.open()
}

/** 分类选择确认 */
const handleCategoryConfirm = (category: consultCategoryVO) => {
  formData.value.categoryId = category.id
  selectedCategoryName.value = category.name
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ConsultInfoApi.getConsultInfo(id)
      formData.value = data
      // 如果有分类ID，需要获取分类名称显示
      if (data.categoryId && data.categoryName) {
        selectedCategoryName.value = data.categoryName
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ConsultInfoVO
    if (formType.value === 'create') {
      await ConsultInfoApi.createConsultInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await ConsultInfoApi.updateConsultInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    categoryId: undefined,
    coverImage: undefined,
    title: undefined,
    content: undefined,
    files: '', // 改为空字符串
    tags: undefined,
    summary: undefined,
    status: 1, // 默认开启
    sort: 0,
    publishTime: undefined,
    source: undefined,
  }
  selectedCategoryName.value = '' // 清空分类名称
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">
.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
</style>